// const apiFetch    = form.dataset.api || form.action || "/api/douyin_fetch/";
// const apiDownload = form.dataset.downloadApi || "/api/douyin_download/";

function getCookie(name) {
  const m = document.cookie.match(new RegExp('(^|; )' + name + '=([^;]*)'));
  return m ? decodeURIComponent(m[2]) : null;
}
function getCsrfToken() {
  const el = document.querySelector('input[name="csrfmiddlewaretoken"]');
  return (el && el.value) || getCookie('csrftoken') || '';
}

// ===== 抖音采集 · Ajax 渲染（卡片风版） =====
document.addEventListener("DOMContentLoaded", function () {
  const form = document.getElementById("dyForm");
  if (!form) return;

  const loadingBox = document.getElementById("dyLoading");
  const resultBox  = document.getElementById("dyResults");

  // 取 API：优先 data-api，其次 form.action，最后兜底
  const api = form.getAttribute("data-api") || form.getAttribute("action") || "/api/douyin_fetch/";

  // CSRF 辅助
  function getCookie(name) {
    const m = document.cookie.match(new RegExp('(^|; )' + name + '=([^;]*)'));
    return m ? decodeURIComponent(m[2]) : null;
  }
  function getCsrfToken() {
    const el = document.querySelector("input[name='csrfmiddlewaretoken']");
    return (el && el.value) || getCookie("csrftoken") || "";
  }

  // —— 统一的单条卡片渲染 —— //
  function renderItem(v) {
    // const placeholderUrl = "{% static 'picture/jinzhu.jpg' %}";
    const cover = v.cover_url
  ? `<img src="${v.cover_url}" alt="封面">`
  : `<img src="${window.DY_PLACEHOLDER}" alt="占位图">`;

    const link = v.play_url || v.page_url || "";

    return `
      <div class="dy-item">
        <div class="dy-row d-flex align-items-center gap-3">
          <div class="dy-thumb-wrap">
            ${cover}
          </div>
          <div class="flex-grow-1">
            <div class="dy-title">${v.title || "（无标题）"}</div>
            <div class="dy-meta">
              ${v.author || "未知"} · ${v.duration || "-"} · HDR:${v.hdr || "-"} · ${v.codec || "-"} 
            </div>
            ${v.page_url ? `<div class="text-muted small mt-1 text-truncate">原页：${v.page_url}</div>` : ""}
            <div class="dy-actions mt-2 d-flex gap-2 flex-wrap">
              <button type="button" class="btn btn-outline-secondary copy-link"
                      data-url="${link}" ${link ? "" : "disabled"}>复制链接</button>
                      
                      
              <a class="btn btn-outline-primary" href="${link || "#"}" target="_blank" rel="noopener"
                 ${link ? "" : 'aria-disabled="true"'}>观看视频</a>
                 
              <button type="button"
        class="btn btn-success download-btn video-download-btn"
        data-url="${link}" ${link ? "" : "disabled"}
        data-title="${(v.title || '').replace(/"/g, '&quot;')}"
        ${v.download_url ? '' : 'disabled'}>
              下载视频
              </button>


            </div>
          </div>
        </div>
      </div>
    `;
  }

  // —— 提交拦截：Ajax 请求 → 渲染 —— //
  // —— 提交拦截：Ajax 请求 → 渲染 —— //
form.addEventListener("submit", async function (e) {
  e.preventDefault();

  // 1) 判定是哪个按钮触发（单 / 主页）
  const submitter = e.submitter;
  const mode = submitter?.value || "single";

  // 2) 组装 FormData，附加 mode
  const fd = new FormData(form);
  fd.set("mode", mode);

  // 3) 选择接口地址：优先 data-api，其次 form.action，最后兜底
  const api =
    form.getAttribute("data-api") ||
    form.getAttribute("action") ||
    "/api/douyin_fetch/";

  // 4) UI：显示加载、清空旧结果
  if (loadingBox) loadingBox.classList.remove("d-none");
  if (resultBox) resultBox.innerHTML = "";

  try {
    // 5) 发请求（注意带上凭据 + CSRF）
    const resp = await fetch(api, {
      method: "POST",
      credentials: "same-origin",
      headers: { "X-CSRFToken": getCsrfToken() },
      body: fd,
    });

    if (!resp.ok) {
      const text = await resp.text();
      throw new Error(`HTTP ${resp.status} ${resp.statusText}\n${text.slice(0, 300)}`);
    }

    // 6) 解析 JSON
    let data;
    try {
      data = await resp.json();
    } catch {
      const text = await resp.text();
      throw new Error("返回的不是 JSON：\n" + text.slice(0, 300));
    }

    if (loadingBox) loadingBox.classList.add("d-none");

    // 7) 校验 & 渲染
    if (!(data && data.ok)) {
      resultBox.innerHTML = `<div class="alert alert-warning">接口异常：${JSON.stringify(data)}</div>`;
      return;
    }

    const list = Array.isArray(data.videos) ? data.videos : [];
    if (!list.length) {
      resultBox.innerHTML = `<div class="dy-empty">没有采集到相关视频，换个关键词试试~</div>`;
      return;
    }

    // 例如：resultBox.innerHTML = list.map(renderItem).join("");
    resultBox.innerHTML = list.map(renderItem).join("");

  } catch (err) {
    if (loadingBox) loadingBox.classList.add("d-none");
    console.error("[DY] 请求失败：", err);
    const safe = String(err).replace(/[<>&]/g, s => ({'<':'&lt;','>':'&gt;','&':'&amp;'}[s]));
    resultBox.innerHTML = `<div class="alert alert-danger">请求失败：<pre class="mb-0">${safe}</pre></div>`;
  }
});





  // —— 复制链接（事件委托） —— //
  document.addEventListener("click", async function (e) {
    const btn = e.target.closest(".copy-link");
    if (!btn) return;
    const url = btn.dataset.url || "";
    if (!url) return;
    try {
      await navigator.clipboard.writeText(url);
      const old = btn.innerText;
      btn.innerText = "已复制";
      btn.classList.remove("btn-outline-secondary");
      btn.classList.add("btn-success");
      setTimeout(() => {
        btn.innerText = old;
        btn.classList.add("btn-outline-secondary");
        btn.classList.remove("btn-success");
      }, 1200);
    } catch (err) {
      alert("复制失败：" + err);
    }
  });
});


// 清空按钮
document.addEventListener("DOMContentLoaded", function () {
  const input = document.querySelector("input[name='query']");
  const btnClear = document.getElementById("btnClear");

  if (btnClear) {
    btnClear.addEventListener("click", () => {
      input.value = "";
      input.focus();
    });
  }
});


// 下载任务：事件委托（点击“下载视频”按钮 → Ajax 提交）
// download_post_form.js
(function () {
  // 可选：从 cookie 里取 Django CSRF（若你已用别的 getCsrfToken，就替换用你的）
  function getCsrfToken() {
    const m = document.cookie.match(/(?:^|; )csrftoken=([^;]+)/);
    return m ? decodeURIComponent(m[1]) : "";
  }

  // 确保有一个隐藏 iframe，用来接收下载（不刷新当前页）
  function ensureIframe() {
    let frame = document.getElementById("dlFrame");
    if (!frame) {
      frame = document.createElement("iframe");
      frame.id = "dlFrame";
      frame.name = "dlFrame";            // 关键：表单 target 指向它
      frame.style.display = "none";
      document.body.appendChild(frame);
    }
    return frame;
  }

  // 提交隐藏表单：POST -> /douyin_download/，浏览器触发下载
  function postDownload({ url, filename, title }) {
    ensureIframe(); // 创建隐藏 iframe

    const form = document.createElement("form");
    form.method = "POST";
    form.action = "/douyin_download/";   // 确保带前导斜杠
    form.target = "dlFrame";             // 不刷新当前页
    form.style.display = "none";

    // CSRF（如果你的 view 上 @csrf_exempt 就可以不传）
    const csrf = getCsrfToken();
    if (csrf) {
      const iCSRF = document.createElement("input");
      iCSRF.type = "hidden";
      iCSRF.name = "csrfmiddlewaretoken";
      iCSRF.value = csrf;
      form.appendChild(iCSRF);
    }

    // 和后端参数名对齐：这里用 u/name/title
    const iu = document.createElement("input");
    iu.type = "hidden";
    iu.name = "u";
    iu.value = url;
    form.appendChild(iu);

    if (filename) {
      const iname = document.createElement("input");
      iname.type = "hidden";
      iname.name = "name";
      iname.value = filename;
      form.appendChild(iname);
    }

    if (title) {
      const ititle = document.createElement("input");
      ititle.type = "hidden";
      ititle.name = "title";
      ititle.value = title;
      form.appendChild(ititle);
    }

    document.body.appendChild(form);
    form.submit();   // ⭐ 触发下载（由浏览器处理 Content-Disposition）
    form.remove();
  }

  // 事件委托：替换你原来的 fetch 逻辑
  document.addEventListener("click", async function (e) {
    const btn = e.target.closest(".download-btn");
    if (!btn) return;

    const url = btn.dataset.url || "";
    const title = (btn.dataset.title || "").trim();
    const filename = (btn.dataset.filename || (title ? title + ".mp4" : "")).trim();
    if (!url) return;

    // UI：禁用按钮、提示状态
    const oldHtml = btn.innerHTML;
    const oldClass = btn.className;
    btn.disabled = true;
    btn.innerHTML = "提交中…";

    try {
      // 直接用隐藏表单 POST，触发下载
      postDownload({ url, filename, title });

      // 简单的成功反馈（下载是浏览器处理的，这里不等结果）
      btn.innerHTML = "已提交";
      btn.className = oldClass.replace("btn-success", "btn-outline-success");

      setTimeout(() => {
        btn.innerHTML = oldHtml;
        btn.className = oldClass;
        btn.disabled = false;
      }, 1500);
    } catch (err) {
      console.error("[Download] 失败：", err);
      btn.innerHTML = "失败，重试";
      btn.className = oldClass.replace("btn-success", "btn-outline-danger");

      setTimeout(() => {
        btn.innerHTML = oldHtml;
        btn.className = oldClass;
        btn.disabled = false;
      }, 1800);
    }
  });
})();

// 按钮冷却
// cooldown_form_safe.js
document.addEventListener("DOMContentLoaded", () => {
  const DEFAULT_COOLDOWN = 8;

  // 仅对 “提交按钮 + 冷却类名” 生效
  document.querySelectorAll('button.cooldown-btn[type="submit"]').forEach((btn) => {
    let cooling = false;
    let timer = null;

    btn.addEventListener("click", (e) => {
      const form = btn.form;
      if (!form) return;

      // 冷却期：阻止再次提交
      if (cooling) {
        e.preventDefault();
        return;
      }

      // 接管默认提交，然后用 requestSubmit(btn) 主动触发表单提交
      e.preventDefault();

      // 触发提交（让你的 form.submit 监听器正常执行，且保留 e.submitter）
      if (typeof form.requestSubmit === "function") {
        form.requestSubmit(btn);
      } else {
        // 兼容旧浏览器：写入隐藏字段，供提交处理时读取
        let hidden = form.querySelector('input[name="__submitter_mode"]');
        if (!hidden) {
          hidden = document.createElement("input");
          hidden.type = "hidden";
          hidden.name = "__submitter_mode";
          form.appendChild(hidden);
        }
        hidden.value = btn.value || "";
        // 触发 submit 事件（旧浏览器可能没有 e.submitter）
        const evt = new Event("submit", { bubbles: true, cancelable: true });
        form.dispatchEvent(evt);
      }

      // —— 从这里开始冷却 UI —— //
      const cooldown = parseInt(btn.dataset.cooldown) || DEFAULT_COOLDOWN;
      const originalText = btn.textContent;
      let left = cooldown;

      cooling = true;
      btn.disabled = true;
      btn.textContent = `请稍等 ${left}s`;

      timer = setInterval(() => {
        left -= 1;
        if (left <= 0) {
          clearInterval(timer);
          cooling = false;
          btn.disabled = false;
          btn.textContent = originalText;
        } else {
          btn.textContent = `请稍等 ${left}s`;
        }
      }, 1000);
    });
  });
});
